package me.lcc.demo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * -演示账号配置和权限配置
 */
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
	
	@Autowired
	UserDetailsService userDetailsService;
	
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		// 自定义获取用户的方法
		auth.userDetailsService(userDetailsService).passwordEncoder(new MyPasswordEncoder());
	}
	
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests()
			// 无需登陆
			.antMatchers("/hello/baby").permitAll() 
		 	// 需要登陆
		 	.antMatchers("/hello/fruit/**").hasAnyRole("USER")
		 	.antMatchers("/admin").hasAnyRole("ADMIN")
		 	// 其他只要登陆认证过都可通过
		 	.anyRequest().authenticated().and().formLogin().and().httpBasic();
	 }
	 
	/**
	 * -密码编码实现类使用明文 
	 */
	 public static class MyPasswordEncoder implements PasswordEncoder {
	    @Override
	    public String encode(CharSequence charSequence) {
	        return charSequence.toString();
	    }

	    @Override
	    public boolean matches(CharSequence charSequence, String s) {
	        return s.equals(charSequence.toString());
	    }
	}
}